import MySQLdb as mysql

# 第1步：创建MySQL数据库连接，获取连接对象
conn = mysql.connect(host='47.104.31.138', port=3306,
                     user='root', password='Luohao.618',
                     database='hrs', charset='utf8mb4',
                     connect_timeout=3)
try:
    # 第2步：基于连接对象创建游标对象
    with conn.cursor(mysql.cursors.DictCursor) as cursor:
        # 第3步：通过游标对象向数据库发出SQL语句并获取执行结果
        cursor.execute('select dno as no, dname as name, dloc as location from tb_dept')
        # 第4步：通过游标抓取数据
        # fecthone() / fecthmany(n) / fetchall()
        for row in cursor.fetchall():
            print(row)
finally:
    # 第5步：关闭连接，释放资源
    conn.close()
